//
//  OBDataRequest.m
//  UCCertificate
//
//  Created by obally on 16/3/14.
//  Copyright © 2016年 ___obally___. All rights reserved.
//

#import "OBDataRequest.h"
#import <AFNetworking/AFNetworkActivityIndicatorManager.h>
#import <SDWebImage/UIImage+GIF.h>

static OBDataRequest *request = nil;
static AFHTTPSessionManager *sessionManager = nil;
@implementation OBDataRequest
+ (OBDataRequest *)request
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        request = [[OBDataRequest alloc]init];
        sessionManager = [AFHTTPSessionManager manager];
        sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    });
    return request;
}
+ (void)startNetWorkMonitoring
{
    /// 开启网络监测
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        UIWindow *window = [UIApplication sharedApplication].delegate.window;
        if (status == AFNetworkReachabilityStatusUnknown) {
            NSLog(@"--- 未知网络 ---");
            [SVProgressHUD showErrorWithStatus:@"未知网络"];
            [OBNotificationCenter postNotificationName:OBNetWorkNotification object:@(AFNetworkReachabilityStatusUnknown)];
        }else if (status == AFNetworkReachabilityStatusNotReachable) {
            NSLog(@"--- 无网络 ---");
            [OBNotificationCenter postNotificationName:OBNetWorkNotification object:@(AFNetworkReachabilityStatusNotReachable)];
             [SVProgressHUD showErrorWithStatus:@"无网络"];
        }else if (status == AFNetworkReachabilityStatusReachableViaWiFi) {
            NSLog(@"--- 无WIFI网络 ---");
            [OBNotificationCenter postNotificationName:OBNetWorkNotification object:@(AFNetworkReachabilityStatusReachableViaWiFi)];
        }else{
            NSLog(@"--- 有蜂窝网络 ---");
            [OBNotificationCenter postNotificationName:OBNetWorkNotification object:@(AFNetworkReachabilityStatusReachableViaWWAN)];
        }
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
- (void)requestWithURL:(NSString *_Nonnull)urlstring
                params:(NSMutableDictionary *_Nullable)params
            httpMethod:(NSString *_Nonnull)httpMethod
       completionblock:(CompletionLoadHandle _Nonnull)completionBlock
           failedBlock:(FailedLoadBlock _Nonnull)failedBlock
{
    [self requestWithURL:urlstring params:params httpMethod:httpMethod progressBlock:nil completionblock:completionBlock failedBlock:failedBlock];
}
- (void)requestWithURL:(NSString *_Nonnull)urlstring
                params:(NSMutableDictionary *_Nullable)params
            httpMethod:(NSString *_Nonnull)httpMethod
         progressBlock:(ProgressBlock _Nullable)progressBlock
       completionblock:(CompletionLoadHandle _Nonnull)completionBlock
           failedBlock:(FailedLoadBlock _Nonnull)failedBlock
{
    [self requestWithURL:urlstring params:params httpMethod:httpMethod progressBlock:progressBlock completionblock:completionBlock failedBlock:failedBlock showView:nil showHUD:NO];
}
- (void)requestWithURL:(NSString *_Nonnull)urlstring
                params:(NSMutableDictionary *_Nullable)params
            httpMethod:(NSString *_Nonnull)httpMethod
       completionblock:(CompletionLoadHandle _Nonnull)completionBlock
           failedBlock:(FailedLoadBlock _Nonnull)failedBlock
               showHUD:(BOOL)showHUD
{
    [self requestWithURL:urlstring params:params httpMethod:httpMethod progressBlock:nil completionblock:completionBlock failedBlock:failedBlock showView:nil showHUD:showHUD];
}
- (void)requestWithURL:(NSString *_Nonnull)urlstring
                params:(NSMutableDictionary *_Nullable)params
            httpMethod:(NSString *_Nonnull)httpMethod
         progressBlock:(ProgressBlock _Nullable)progressBlock
       completionblock:(CompletionLoadHandle _Nonnull)completionBlock
           failedBlock:(FailedLoadBlock _Nonnull)failedBlock
              showView:(UIView *_Nullable)showView
               showHUD:(BOOL)showHUD
{
    if (params == nil) {
        params = [NSMutableDictionary dictionary];
    }
    // 设置超时时间
    [sessionManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    sessionManager.requestSerializer.timeoutInterval = 20.f;
    [sessionManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    if ([httpMethod isEqualToString:@"GET"]) {
        //发送GET请求
        [sessionManager GET:urlstring parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            NSLog(@"%lld", downloadProgress.totalUnitCount);
            if (progressBlock != nil) {
                progressBlock(downloadProgress);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@", responseObject);
            id JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"请求成功JSON:%@", JSON);
            if (completionBlock != nil) {
                completionBlock(JSON);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
            if (failedBlock != nil) {
                failedBlock([error localizedDescription]);
            }
            if (showHUD == YES) {
                [SVProgressHUD dismiss];
            }
        }];
        
    }else if ([httpMethod isEqualToString:@"POST"]) {
        //发送POST请求
        BOOL isFile = NO;
        for (NSString *key in params) {
            id value = params[key];
            if (value != nil) {
                if ([value isKindOfClass:[NSData class]]) {
                    isFile = YES;
                    break;
                }
            }
        }
        if (!isFile) {
            NSString *paramsStr = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
            NSLog(@"请求地址：  %@, 请求参数： %@\n", urlstring, paramsStr);
            //如果参数中没有文件
            [sessionManager POST:urlstring parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
                if (progressBlock != nil) {
                    progressBlock(uploadProgress);
                }
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"请求成功:%@,JSON:  %@",task.originalRequest.URL.absoluteString, [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);
                if (completionBlock != nil) {
                    completionBlock(JSON);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failedBlock != nil) {
                    failedBlock([error localizedDescription]);
                }
            }];
        } else {
            //如果参数中带有参数
            [sessionManager POST:urlstring parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                for (NSString *key in params) {
                    id value = params[key];
                    if ([value isKindOfClass:[NSData class]]) {
                        //将文件添加到formData中
                        [formData appendPartWithFileData:value
                                                    name:key
                                                fileName:@"aaa.jpg"
                                                mimeType:@"image/jpeg"];
                    }
                }
                
            } progress:^(NSProgress * _Nonnull uploadProgress) {
                if (progressBlock != nil) {
                    progressBlock(uploadProgress);
                }
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"请求成功:%@,JSON:  %@",task.originalRequest.URL.absoluteString, JSON);
                if (completionBlock != nil) {
                    completionBlock(JSON);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failedBlock != nil) {
                    failedBlock([error localizedDescription]);
                }
                
            }];
        }
    }
}


@end
